package com.itheima.test5;

import org.junit.Before;
import org.junit.Test;

import java.lang.reflect.Field;

/**
 * @Author:gy
 * @Date: 2025/09/06 11:12
 * @Description:
 */
public class Demo {
    Class clazz;
    @Before
   public void getClazz() throws Exception {
        clazz = Class.forName("com.itheima.test5.Teacher");
   }
   //获取公共字段
    @Test
    public void method(){
        for (Field field : clazz.getFields()) {
            System.out.println(field);
        }

    }
    //获取所有字段包括私有
    @Test
    public void method1(){
        for (Field field : clazz.getDeclaredFields()) {
            System.out.println(field);
        }

    }
    //获取单个公共的字段
    @Test
    public void method2() throws Exception {
        Field age = clazz.getField("age");
        Object o = clazz.newInstance();
        age.set(o,18);
        Object o1 = age.get(o);
        System.out.println(o1);
        //System.out.println(age);
        System.out.println(o);
    }
    //获取单个所有的字段
    @Test
    public void method3() throws Exception {
        Field money = clazz.getDeclaredField("money");
        Object o = clazz.newInstance();
        //将私有的设置为取消检查  暴力访问
        money.setAccessible(true);
        Object m = money.get(o);
        money.set(o,600);
        System.out.println(m);
        System.out.println(o);
        //System.out.println(money);
    }
}
